package com.team.teamuserservice.listener;

import cn.hutool.json.JSONUtil;
import com.team.teamuserservice.entity.dto.DelayRescueMessage;
import com.team.teamuserservice.service.BroadcastService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 延迟消息监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DelayMessageListener {

    private final BroadcastService broadcastService;

    /**
     * 监听延迟队列中的救援消息 , 一旦有消息赶紧处理
     */
    @RabbitListener(queues = "delay.queue")
    public void handleDelayRescueMessage(String message) {
        try {
            log.info("收到延迟救援消息: {}", message);
            //解析
            DelayRescueMessage delayRescueMessage = JSONUtil.toBean(message, DelayRescueMessage.class);
            
            if (delayRescueMessage == null || delayRescueMessage.getUserLocation() == null) {
                log.warn("延迟救援消息格式错误");
                return;
            }
            
            // 判断延迟消息的类型 , 根据延迟类型进行不同距离的广播
            switch (delayRescueMessage.getDelayType()) {
                case 1:
                    log.info("执行5km广播，任务ID: {}", delayRescueMessage.getRescueTaskId());
                    broadcastService.broadcastTo5kmMerchants(delayRescueMessage);
                    break;
                case 2:
                    log.info("执行10km广播，任务ID: {}", delayRescueMessage.getRescueTaskId());
                    broadcastService.broadcastTo10kmMerchants(delayRescueMessage);
                    break;
                default:
                    log.warn("未知的延迟类型: {}", delayRescueMessage.getDelayType());
                    break;
            }
            
        } catch (Exception e) {
            log.error("处理延迟救援消息失败", e);
        }
    }
} 